package com.example.umbrella;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.umbrella.adapter.CharacteristicAdapter;
import com.example.umbrella.model.CharacteristicModel;
import com.google.android.material.snackbar.Snackbar;

import java.util.ArrayList;
import java.util.List;

public class DeviceDetailActivity extends AppCompatActivity {
    private BluetoothGatt bluetoothGatt;
    private TextView statusText;
    private String targetServiceUuid;
    private RecyclerView characteristicsList;
    private CharacteristicAdapter characteristicAdapter;
    private View loadingView;
    private TextView loadingText;
    private View contentView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_detail);

        initViews();
        initToolbar();
        
        String deviceAddress = getIntent().getStringExtra("deviceAddress");
        targetServiceUuid = getIntent().getStringExtra("serviceUuid");
        
        if (deviceAddress != null) {
            showLoading("正在连接设备...");
            connectToDevice(deviceAddress);
        }
    }

    private void initToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(v -> onBackPressed());
    }

    private void initViews() {
        loadingView = findViewById(R.id.loading_layout);
        loadingText = loadingView.findViewById(R.id.loading_text);
        contentView = findViewById(R.id.content_container);
        
        statusText = findViewById(R.id.status_text);
        characteristicsList = findViewById(R.id.characteristics_list);
        characteristicsList.setLayoutManager(new LinearLayoutManager(this));
        characteristicAdapter = new CharacteristicAdapter();
        characteristicsList.setAdapter(characteristicAdapter);
    }

    private void showLoading(String message) {
        runOnUiThread(() -> {
            loadingView.setVisibility(View.VISIBLE);
            loadingText.setText(message);
            contentView.setVisibility(View.GONE);
        });
    }

    private void hideLoading() {
        runOnUiThread(() -> {
            loadingView.setVisibility(View.GONE);
            contentView.setVisibility(View.VISIBLE);
        });
    }

    private void connectToDevice(String deviceAddress) {
        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
        
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) 
            != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "缺少蓝牙连接权限", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
        bluetoothGatt = device.connectGatt(this, false, gattCallback);
    }

    private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                if (newState == BluetoothGatt.STATE_CONNECTED) {
                    runOnUiThread(() -> {
                        statusText.setText("已连接");
                        showLoading("正在获取设备信息...");
                    });
                    if (ActivityCompat.checkSelfPermission(DeviceDetailActivity.this, 
                        Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                        gatt.discoverServices();
                    }
                } else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
                    runOnUiThread(() -> {
                        hideLoading();
                        statusText.setText("连接断开");
                        showError("设备连接已断开");
                    });
                }
            } else {
                runOnUiThread(() -> {
                    hideLoading();
                    statusText.setText("连接失败");
                    showError("连接失败，错误码: " + status);
                });
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                runOnUiThread(() -> showLoading("正在读取特征值..."));
                readCharacteristics(gatt);
            } else {
                runOnUiThread(() -> {
                    hideLoading();
                    showError("获取服务失败");
                });
            }
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, 
                                       BluetoothGattCharacteristic characteristic, 
                                       int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                byte[] data = characteristic.getValue();
                runOnUiThread(() -> {
                    characteristicAdapter.updateCharacteristicValue(
                        characteristic.getUuid().toString(), 
                        data
                    );
                    hideLoading();
                });
            }
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, 
                                          BluetoothGattCharacteristic characteristic) {
            byte[] data = characteristic.getValue();
            runOnUiThread(() -> {
                characteristicAdapter.updateCharacteristicValue(
                    characteristic.getUuid().toString(), 
                    data
                );
            });
        }
    };

    private void readCharacteristics(BluetoothGatt gatt) {
        List<CharacteristicModel> characteristicsList = new ArrayList<>();
        
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) 
                != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        for (BluetoothGattService service : gatt.getServices()) {
            for (BluetoothGattCharacteristic characteristic : service.getCharacteristics()) {
                int properties = characteristic.getProperties();
                boolean isReadable = (properties & BluetoothGattCharacteristic.PROPERTY_READ) != 0;
                boolean isWritable = (properties & BluetoothGattCharacteristic.PROPERTY_WRITE) != 0 
                        || (properties & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) != 0;
                
                CharacteristicModel model = new CharacteristicModel(
                    characteristic.getUuid().toString(),
                    new byte[0],  // 初始为空字节数组
                    isWritable,
                    isReadable
                );
                characteristicsList.add(model);
                
                // 如果可读，则读取特征值
                if (isReadable) {
                    gatt.readCharacteristic(characteristic);
                }
            }
        }
        
        runOnUiThread(() -> {
            characteristicAdapter.setCharacteristics(characteristicsList);
        });
    }

    private void showError(String message) {
        runOnUiThread(() -> {
            Snackbar.make(findViewById(android.R.id.content), message, Snackbar.LENGTH_LONG)
                    .setBackgroundTint(getColor(R.color.error_background))
                    .setTextColor(getColor(R.color.white))
                    .show();
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bluetoothGatt != null) {
            if (ActivityCompat.checkSelfPermission(this, 
                Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                bluetoothGatt.close();
            }
            bluetoothGatt = null;
        }
    }
}